<?php

namespace App\Http\Controllers\Login;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Manger\Manger;
use App\Services\Common\Common;
use App\Services\Manger\MangerAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class LoginController extends Controller
{

    /**
     * 获取账套列表
     */
    public function getcompanylist(Request $request)
    {

        $query = Company::where('status', 1)->orderBy('create_at', 'desc');
        $list = $query->select(['id', 'company_name', 'other_title', 'status','cpd_id'])->get()->toArray();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['list' => $list]]);
    }
    /**
     * 业务端登陆
     */
    public function dologin(Request $request)
    {
        try {
            $this->validate($request, [
                'username' => 'required',
                'password' => 'required',
                'cpid' => 'required',
            ]);
        } catch (\Exception $exception) {
            return response()->json(['code' => '001', 'msg' => '请确保账套已选择以及帐号或者密码不能为空']);
        }
        if (strlen($request->password) != 32) {
            return response()->json(['code' => '001', 'msg' => '密码长度不规范']);
        }
        // $info = Manger::where('cpid', $request->cpid)->where('username', $request->username)->where('password', MD5(MD5('huakun_' . $request->password)))->first();
        $info = Manger::where('cpid', $request->cpid)->where('username', $request->username)->where('password', MD5($request->password))->first();
        if ($info && $info->status == 1) {

            if ($info->cpid != $request->cpid) {
                return response()->json(['code' => '001', 'msg' => '账套信息不匹配']);
            }
            $companyinfo = Company::where([['id', $info->cpid]])->first();

            $info->utypes=explode(',',$info->utypes);

            $token = md5(time() . mt_rand(1000, 9999) . '__' . $info->id);
            /**
             * 增加公司id
            */
            $org_id = Company::where('id',$info->cpid)->value('org_id');
            $info->org_id = $org_id;

            Redis::set($token, json_encode($info));
            MangerAccount::storeTokenKey($token, $info->id);
            Manger::where(['id' => $info->id])->update(['lastlogin_ip' => getClientIp(), 'lastlogin_at' => time()]);

            return response()->json([
                'code' => '000',
                'msg' => '登录成功',
                'data' => ['token' => $token, 'info' => ['id'=>$info->id,'username' => $info->username, 'mobile' => $info->mobile, 'realname' => $info->realname], 'companyinfo' => $companyinfo,'utypes'=>$info->utypes]
            ]);
        } else {
            return response()->json(['code' => '001', 'msg' => '账号或密码错误']);
        }
    }

    /**
     * 获取可切换的账套
     */
    public function getchangecompanylist(Request $request)
    {
        $token = $request->header('token');
        $memberinfo = Redis::get($token);
        if (!$token || !$memberinfo) {
            return response()->json(['code' => '001', 'msg' => '登录失效无法切换账套']);
        }
        $memberinfo = json_decode($memberinfo, true);
        $info = Manger::where(['id' => $memberinfo['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '登录失效无法切换账套']);
        }

        $cpidlist = Manger::where([['cpid', '<>', $info->cpid], ['username', $info->username]])->pluck('cpid');

        $query = Company::where('status', 1)->whereIn('id', $cpidlist)->orderBy('create_at', 'desc');
        $list = $query->select(['id', 'company_name', 'other_title', 'status'])->get()->toArray();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['list' => $list]]);
    }

    /**
     * 切换账套
     */
    public function dologinchangecompany(Request $request)
    {
        try {
            $this->validate($request, [
                'password' => 'required',
                'cpid' => 'required',
            ]);
        } catch (\Exception $exception) {
            return response()->json(['code' => '001', 'msg' => '请确保账套已选择以及密码不能为空']);
        }



        if (strlen($request->password) != 32) {
            return response()->json(['code' => '001', 'msg' => '密码长度不规范']);
        }


        $token = $request->header('token');
        $memberinfo = Redis::get($token);
        if (!$token || !$memberinfo) {
            return response()->json(['code' => '001', 'msg' => '登录失效无法切换账套']);
        }
        $memberinfo = json_decode($memberinfo, true);
        $info = Manger::where(['id' => $memberinfo['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '登录失效无法切换账套']);
        }


        $info = Manger::where('cpid', $request->cpid)->where('username', $info->username)->where('password', MD5($request->password))->first();
        if ($info && $info->status == 1) {

            if ($info->cpid != $request->cpid) {
                return response()->json(['code' => '001', 'msg' => '账套信息不匹配']);
            }
            $companyinfo = Company::where([['id', $info->cpid]])->first();

            $info->utypes=explode(',',$info->utypes);
            //切换前的账号退出登录

            Redis::delete($token);
            MangerAccount::cleartokenkey($memberinfo['id']);

            $token = md5(time() . mt_rand(1000, 9999) . '__' . $info->id);
            /**
             * 增加公司id
             */
            $org_id = Company::where('id',$info->cpid)->value('org_id');
            $info->org_id = $org_id;
            Redis::set($token, json_encode($info));
            MangerAccount::storeTokenKey($token, $info->id);
            Manger::where(['id' => $info->id])->update(['lastlogin_ip' => getClientIp(), 'lastlogin_at' => time()]);



            return response()->json([
                'code' => '000',
                'msg' => '登录成功',
                'data' => ['token' => $token, 'info' => ['username' => $info->username, 'mobile' => $info->mobile, 'realname' => $info->realname], 'companyinfo' => $companyinfo,'utypes'=>$info->utypes]
            ]);
        } else {
            return response()->json(['code' => '001', 'msg' => '帐号或者密码错误']);
        }
    }

    /**
     * 业务端退出登录
     */
    public function dologinout(Request $request)
    {
        $token = $request->header('token');
        $memberinfo = Redis::get($token);
        if (!$token || !$memberinfo) {
            return response()->json(['code' => '001', 'msg' => '非法访问']);
        }
        $memberinfo = json_decode($memberinfo, true);
        $info = Manger::where(['id' => $memberinfo['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        Redis::delete($token);
        MangerAccount::cleartokenkey($memberinfo['id']);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 业务端更改密码
     */
    public function changepassword(Request $request)
    {
        $token = $request->header('token');
        $memberinfo = Redis::get($token);
        if (!$token || !$memberinfo) {
            return response()->json(['code' => '001', 'msg' => '非法访问']);
        }


        $memberinfo = json_decode($memberinfo, true);
        $info = Manger::where(['id' => $memberinfo['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $oldpassword = $request->oldpassword;
        $password = $request->password;
        $repassword = $request->repassword;

        if ((strlen($oldpassword) < 5 || strlen($oldpassword) > 20) || (strlen($password) < 5 || strlen($password) > 20) || (strlen($repassword) < 5 || strlen($repassword) > 20)) {
            return response()->json(['code' => '001', 'msg' => '请保持密码长度为5~20位']);
        }

        if ($oldpassword == '' || $password == '' || $repassword == '' || $password != $repassword) {
            return response()->json(['code' => '001', 'msg' => '请确保输入框完整']);
        }
        if (MD5(MD5('huakun_' . $oldpassword)) != $info->password) {
            return response()->json(['code' => '001', 'msg' => '原密码不正确']);
        }

        Manger::where(['id' => $memberinfo['id']])->update(['password' => MD5(MD5('huakun_' . $password))]);

        //清除缓存
        MangerAccount::clearTokenKey($memberinfo['id']);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
